package com.pingan.haofang.searchcloud.api.query.parser;

import com.pingan.haofang.searchcloud.api.matedata.IndexMetadataHolder;
import com.pingan.haofang.searchcloud.api.query.parser.context.SqlExecutionContext;
import com.pingan.haofang.searchcloud.api.query.parser.element.QueryBlock;
import com.pingan.haofang.searchcloud.api.query.parser.element.SelectStatement;
import com.pingan.haofang.searchcloud.api.query.parser.exception.SqlParseException;
import com.pingan.haofang.searchcloud.api.query.parser.visitor.SelectStatementVisitor;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.Select;

/**
 * ClassName: SelectStatementParser <br>
 * Function: select语句解析器
 *
 * @author LUYI374
 * @version 1.0.0
 * @since 1.0.0
 * @date 20150524
 */
public class SelectStatementParser {

    public static SelectStatement parse(String sql, IndexMetadataHolder holder) {
        try {
            SqlExecutionContext context = new SqlExecutionContext();

            context.setSql(sql);
            context.setMetadataHolder(holder);

            Statement statement = CCJSqlParserUtil.parse(sql);

            Select select = (Select) statement;
            SelectStatement stmt = new SelectStatement();

            SelectStatementVisitor visitor = new SelectStatementVisitor();
            visitor.setContext(context);
            select.getSelectBody().accept(visitor);
            stmt.setSelect(select);
            QueryBlock queryBlock = visitor.getQueryBlock();
            stmt.setQueryBlock(queryBlock);
            stmt.setSqlPlain(context.getSql());
            stmt.setMeta(visitor.getMeta());
            return stmt;
        } catch (Throwable e) {
            throw new SqlParseException(e.getMessage(), e);
        }
    }


}
